import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.util.*;

/**
 * @author	Huangwm
 * @description	Push Lims Sampling Records to EAP
 */
public class ModeApi_Records {
	
	private String systemid = "FenBeiTong";//系统标识
	private String d_password = "FenBeiTong";//接口授权密码
    
	public static void main(String[] args) {
        ModeApi_Records test = new ModeApi_Records();
        JSONObject total = new ModeApi_Total().push();
        Integer pageCount = total.getJSONObject("result").getInteger("pageCount");
        if(pageCount>0){
            int pageSize = 100;
            for(int i=1;i<=(pageCount/pageSize)+1;i++){
                System.err.println("第"+i+"次获取 请求参数");
                test.push(i,pageSize);
            }
        }

	}
	
	public synchronized void push(int page,int pageSize){
		CloseableHttpResponse response;// 响应类,
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //接口url
        HttpPost httpPost = new HttpPost("http://219.131.223.76:8888/api/cube/restful/interface/getModeDataPageList/ContractToFBT");

        //总参数
        JSONObject  requestParams = new JSONObject();
        JSONArray dataParams = new JSONArray();

        Map pageInfo = new HashMap<>();
        pageInfo.put("pageNo",page);
        pageInfo.put("pageSize",pageSize);

        //header
        String currentDate = getCurrentDate();
        String currentTime = getCurrentTime();
        String currentTimeTamp = getTimestamp();
        Map header = new HashMap<>();
        String md5Source = systemid+d_password+currentTimeTamp;
        String md5OfStr = getMD5Str(md5Source).toLowerCase();
        //header里的参数
        header.put("systemid",systemid);
        header.put("currentDateTime",currentTimeTamp);
        header.put("Md5",md5OfStr);//Md5是：系统标识+密码+时间戳 并且md5加密的结果

        //operationinfo
        Map operationinfo = new HashMap<>();
        operationinfo.put("operator", "1");//这里要使用id

        //mainTable
        Map mainTable = new HashMap<>();

        requestParams.put("operationinfo", operationinfo);
        requestParams.put("mainTable", mainTable);
        requestParams.put("header", header);
        requestParams.put("pageInfo",pageInfo);

        Map<String,Object> datajson = new HashMap<>();
        datajson.put("datajson", requestParams);
        System.err.println(datajson);
        List<NameValuePair> nvps = new ArrayList();
        if(requestParams!=null){
            for (Map.Entry<String,Object> entry : datajson.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), JSONObject.toJSONString(entry.getValue())));
            }
        }
        long time = System.currentTimeMillis();
        try{
            httpPost.addHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8");
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));

            response = httpClient.execute(httpPost);
            if (response != null && response.getEntity() != null) {
                String result = EntityUtils.toString(response.getEntity());
                //todo这里处理返回信息
                System.err.println(JSONObject.parseObject(result).getJSONArray("result"));
            }else{
                System.err.println("获取数据失败，请查看日志"+currentDate+" "+currentTime);
            }
        }catch (Exception e){
            System.err.println("请求失败"+currentDate+" "+currentTime+"====errormsg:"+e.getMessage());
        }
        time = System.currentTimeMillis();
        System.err.println("总耗时（秒）：" + (time / 1000/1000/60));
	}
	
	
    public String getMD5Str(String plainText){
        //定义一个字节数组
        byte[] secretBytes = null;
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            //对字符串进行加密
            md.update(plainText.getBytes());
            //获得加密后的数据
            secretBytes = md.digest();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有md5这个算法！");
        }
        //将加密后的数据转换为16进制数字
        String md5code = new BigInteger(1, secretBytes).toString(16);
        // 如果生成数字未满32位，需要前面补0
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }

    public static String getCurrentTime() {
        Date newdate = new Date();
        long datetime = newdate.getTime();
        Timestamp timestamp = new Timestamp(datetime);
        String currenttime = (timestamp.toString()).substring(11, 13) + ":" + (timestamp.toString()).substring(14, 16) + ":"
                + (timestamp.toString()).substring(17, 19);
        return currenttime;
    }

    public static String getCurrentDate() {
        Date newdate = new Date();
        long datetime = newdate.getTime();
        Timestamp timestamp = new Timestamp(datetime);
        String currentdate = (timestamp.toString()).substring(0, 4) + "-" + (timestamp.toString()).substring(5, 7) + "-"
                + (timestamp.toString()).substring(8, 10);
        return currentdate;
    }

    /**
       * 获取当前日期时间。 YYYY-MM-DD HH:MM:SS
     * @return		当前日期时间
     */
    public static String getCurDateTime() {
        Date newdate = new Date();
        long datetime = newdate.getTime();
        Timestamp timestamp = new Timestamp(datetime);
        return (timestamp.toString()).substring(0, 19);
    }

    /**
     * 获取时间戳   格式如：19990101235959
     * @return
     */
    public static String getTimestamp(){
        return getCurDateTime().replace("-", "").replace(":", "").replace(" ", "");
    }

    public static int getIntValue(String v, int def) {
        try {
            return Integer.parseInt(v);
        } catch (Exception ex) {
            return def;
        }
    }

    public static String null2String(Object s) {
        return s == null ? "" : s.toString();

    }
}
